﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace quickfileindexer.Components
{
    public partial class ResultForm : Form
    {
        String Name;
        public ResultForm(List<string> files,string name)
        {
            this.Name = name;
            this.Text = "Search Result of \""+name+"\" in "+Environment.CurrentDirectory;
            InitializeComponent();
            this.comboBox1.Text = "(Select a path...)";
            this.label1.Text = files.Count + " file(s) matched.";
            if (files.Count > 100) this.label2.Text = "You might need to provide a more precise keyword.";
            if (files.Count == 0) this.label2.Text = "Providing a shorter keyword might help.";
            foreach (string file in files)
            {
                this.comboBox1.Items.Add(file);
            }
            this.comboBox1.MaxDropDownItems = 35;
        }


        private void ResultForm_Load(object sender, EventArgs e)
        {

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            FileInfo fileInfo = new FileInfo(comboBox1.Text);
            fileInfoLabel.Text = "File Info: \n\nSize: " + fileInfo.Length / 1024 + " KB" +
            "\nAttributes: " + fileInfo.Attributes +
            "\nExtension Name: " + fileInfo.Extension +
            "\nCreation Time: " + fileInfo.CreationTime +
            "\nLast Time Changed: " + fileInfo.LastWriteTime +
            "\nLast Access Time: " + fileInfo.LastAccessTime +
            "\nIs Read Only: " + fileInfo.IsReadOnly;

            string cksum; CalCheckSum(GetHex(comboBox1.Text),out cksum);
            label3.Text = "CheckSum: " + cksum;

        }

        private string GetHex(string file)
        {
            byte[] bytes = File.ReadAllBytes(file);
            return BitConverter.ToString(bytes).Replace("-","");
        }
        private bool CalCheckSum(string hexString, out string ckSum)
        {
            try
            {
                ckSum = string.Empty;
                if (hexString.Length % 2 != 0)
                    return false;
                byte[] buffer = new byte[hexString.Length / 2];
                for (int i = 0; i < hexString.Length; i = i + 2)

                {
                    buffer[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
                }
                int sum = 0;
                for (int i = 0; i < buffer.Length - 2; i++)//Stop Bit 的值即为CheckSum
                {

                    sum += (int)buffer[i];
                }
                string cks = sum.ToString("X2");
                if (cks.Length > 2)
                    ckSum = cks.Substring(cks.Length - 2, 2);
                else
                    ckSum = cks;
                return true;
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
                ckSum = "";
                return false;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (this.comboBox1.Text == "(Select a path...)") return;
            try
            {
                Process.Start(this.comboBox1.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (this.comboBox1.Text == "(Select a path...)") return;
            try
            {
                ExplorerFile(comboBox1.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }




        /// <summary>
        /// 打开路径并定位文件...对于@"h:\Bleacher Report - Hardaway with the safe call ??.mp4"这样的，explorer.exe /select,d:xxx不认，用API整它
        /// </summary>
        /// <param name="filePath">文件绝对路径</param>
        [DllImport("shell32.dll", ExactSpelling = true)]
        private static extern void ILFree(IntPtr pidlList);

        [DllImport("shell32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
        private static extern IntPtr ILCreateFromPathW(string pszPath);

        [DllImport("shell32.dll", ExactSpelling = true)]
        private static extern int SHOpenFolderAndSelectItems(IntPtr pidlList, uint cild, IntPtr children, uint dwFlags);

        public static void ExplorerFile(string filePath)
        {
            if (!File.Exists(filePath) && !Directory.Exists(filePath))
                return;

            if (Directory.Exists(filePath))
                Process.Start(@"explorer.exe", "/select,\"" + filePath + "\"");
            else
            {
                IntPtr pidlList = ILCreateFromPathW(filePath);
                if (pidlList != IntPtr.Zero)
                {
                    try
                    {
                        Marshal.ThrowExceptionForHR(SHOpenFolderAndSelectItems(pidlList, 0, IntPtr.Zero, 0));
                    }
                    finally
                    {
                        ILFree(pidlList);
                    }
                }
            }
        }
    }
}
